export default {
  data() {
    return {
      page: 1,
      limit: 20,
      total: 0,
      list: [],
      loading: false,
      noMore: false,
      keyword: "",
    };
  },
  watch: {
    keyword() {
      this.getList();
    },
  },
  onPullDownRefresh() {
    this.getList(0);
  },
  onReachBottom() {
    if (this.total && !this.noMore) {
      this.getList(true);
    }
  },
  methods: {
    async getList(more) {
      try {
        if (this.loading) return;
        this.loading = more ? 2 : 1;
        if (more) {
          this.page++;
        } else {
          this.page = 1;
          this.noMore = false;
        }
        const params = {
          _page: this.page,
          _limit: this.limit,
        };
        if (this.keyword) {
          const short = this.keyword.substring(0, 7);
          params[this.searchKey || "name"] = `%${short}%`;
        }
        const storKey = "list-" + this.listApi;
        if (this.page == 1 && !this.keyword) {
          const data = await uni.$h.getStorage(storKey);
          if (data) {
            this.list = data.items;
            this.total = data.total;
            this.noMore = this.list.length < this.limit;
            params._cache = data.time;
          }
          // console.log(storKey, data);
        }
        if (this.page == 1) {
          if (!this.list.length) {
            uni.startPullDownRefresh();
          } else if (more !== 0) {
            this.$loading();
            uni.$h.scrollToTop();
          }
        }
        const { data } = await uni.$api.get(this.listApi, {
          params,
        });
        const { items, total } = data;
        if (items) {
          // 服务端判断最后更新时间 不大于_cache，可不返回items
          this.total = total;
          this.noMore = items.length < this.limit;
          if (more) {
            this.list = [...this.list, ...items];
          } else {
            this.list = items;
            if (!this.keyword) {
              await uni.$h.setStorage(storKey, data);
            }
          }
        }
      } catch (error) {
        console.log(error);
      }
      uni.hideLoading();
      this.loading = false;
      uni.stopPullDownRefresh();
    },
  },
};
